package Utils;

import Book.Book;
import com.bit.utils.FileUtils;
import Book.PairOfUidAndBookId;
import java.io.IOException;

public class AnalyzingBorrowBook {
    public void storeObject(PairOfUidAndBookId[] pairOfUidAndBookId, String filename) throws IOException {
        int bookuselen = 0;
        for (int i = 0; i < pairOfUidAndBookId.length; i++) {
            if (pairOfUidAndBookId[i] != null){
                bookuselen++;
            }
        }
        StringBuilder jsonArray =new StringBuilder();
        for (int i = 0; i < bookuselen; i++) {
            if (pairOfUidAndBookId[i] != null){
                jsonArray.append(pairOfUidAndBookId[i].toJson());
            }
            if (i != bookuselen - 1){
                jsonArray.append("\n");
            }
            FileUtils.writeFile(jsonArray.toString(),filename);
        }
    }
    public PairOfUidAndBookId[] loadObject(String filename) throws IOException {
        String concent = FileUtils.readFile(filename);
        if (concent == null || concent.isEmpty()){
            System.out.println("没有数据"+ filename);
            return null;
        }
        String[] bookjson = concent.split("\n");
        PairOfUidAndBookId[] booklist = new PairOfUidAndBookId[bookjson.length];

        for (int i = 0; i < bookjson.length; i++) {
            PairOfUidAndBookId book = new PairOfUidAndBookId();
            String[] uidAndBookId = bookjson[i].split(",");
            book.setBookid(Integer.parseInt(uidAndBookId[0]));
            book.setUserid(Integer.parseInt(uidAndBookId[1]));
            booklist[i] = book;
        }
        return booklist;
    }
}
